package com.youdianstar.app.common.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * File: AppUtil Tool
 * Author: 82149 Create: 2019/4/23 15:49
 * Changes (from 2019/4/23)
 * --------------------------------------------------
 * describe:
 * ---------------------------------------------------
 */
public class Tool {

    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException ignored) {
        }
        return "";
    }

    /**
     * 复制内容到剪切板
     *
     * @param copyStr 文本
     */
    public static boolean copy(Context context, String copyStr) {
        try {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", copyStr);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取粘贴板内容
     *
     * @param context 上下文
     */
    public static String getClipText(Context context) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData data = cm.getPrimaryClip();
        if (null == data)
            return null;
        ClipData.Item item = data.getItemAt(0);
        if (null == item)
            return null;
        return (null==item.getText() ? "":item.getText().toString());
    }

    /**
     * 清空剪贴板内容
     */
    public static void clearClipboard(Context context) {
        ClipboardManager manager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (manager != null) {
            try {
//                manager.setPrimaryClip(ClipData.newPlainText(null, null));
                manager.setPrimaryClip(manager.getPrimaryClip());
                manager.setText(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 给textVIew添加下划线
     *
     * @param view 文本控件
     */
    public static void setUnderLine(Context context, TextView view, String msg, int colorId){
        Paint linePaint = new Paint();
        linePaint.setColor(ContextCompat.getColor(context,colorId));
        linePaint.setFlags(Paint.UNDERLINE_TEXT_FLAG);
        view.setPaintFlags(linePaint.getFlags());
        view.setText(msg);
    }

    /**
     * 给textVIew添加中划线
     *
     * @param tv 文本控件
     */
    public static void setViewCenterLine(TextView tv, int color){
        Paint paint = tv.getPaint();
        paint.setColor(ContextCompat.getColor(tv.getContext(),color));
        paint.setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        paint.setAntiAlias(true);
    }

    /**
     * 发送邮件
     *
     * @param email 邮件
     */
    public static void callEmail(Activity context, String email) {
        try {
            Intent data = new Intent(Intent.ACTION_SENDTO);
            data.setData(Uri.parse("mailto:" + email));
            data.putExtra(Intent.EXTRA_SUBJECT, "Example title");
            data.putExtra(Intent.EXTRA_TEXT, "Base msg");
            context.startActivity(data);
        } catch (Exception ignored) {
        }
    }

    /**
     * 调起呼叫
     *
     * @param phone 手机
     */
    public static void callPhone(Activity context, String phone) {
        //开启系统拨号器
        try {
            Intent intent = new Intent();
            //intent.setAction(Intent.ACTION_CALL);
            intent.setAction(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + phone));
            context.startActivity(intent);
        } catch (Exception ignored) {
        }
    }

    /**
     * 拉起 WhatsApp
     *
     * @param context activity
     */
    public static void callWhatsApp(Activity context, String number) {
        String url = "https://api.whatsapp.com/send?phone=" + number;
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        context.startActivity(i);
    }

    /**
     * 邀请好友
     *
     * @param url 邀请内容链接
     */
    public static void shareInvite(Activity context, String url) {
        // 调用系统分享分享出去
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, url);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        //切记需要使用Intent.createChooser，否则会出现别样的应用选择框，您可以试试
        shareIntent = Intent.createChooser(shareIntent, "Here is the title of Select box");
        context.startActivity(shareIntent);
    }


    /**
     * 邀请好友
     *
     * @param url 邀请内容链接
     */
    public static void shareContainUrl(Activity context,String msg, String url) {
        // 调用系统分享分享出去
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, url);
        shareIntent.putExtra(Intent.EXTRA_TITLE, msg);
        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        //切记需要使用Intent.createChooser，否则会出现别样的应用选择框，您可以试试
        shareIntent = Intent.createChooser(shareIntent, "Here is the title of Select box");
        context.startActivity(shareIntent);
    }

    /**
     * 分享功能
     *
     * @param context
     * @param activityTitle
     * @param msgTitle  消息标题
     * @param msgText 消息内容
     * @param imgPath 图片路径，不分享图片则传null
     */
    public static void shareMsg(Activity context,String activityTitle, String msgTitle, String msgText, String imgPath) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        if (imgPath == null || imgPath.equals("")) {
            // 纯文本
            intent.setType("text/plain");
        } else {
            File f = new File(imgPath);
            if (f != null && f.exists() && f.isFile()) {
                intent.setType("image/jpg");
                Uri u = Uri.fromFile(f);
                intent.putExtra(Intent.EXTRA_STREAM, u);
            }
        }
        intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
        intent.putExtra(Intent.EXTRA_TEXT, msgText);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(Intent.createChooser(intent, activityTitle));
    }

    /**
     * 跳转Google 商店
     *
     * @param context 上下文
     */
    public static void startStoreNow(final Context context) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=" + context.getPackageName()));
            //这里对应的是谷歌商店，跳转别的商店改成对应的即可
            intent.setPackage("com.android.vending");
            if (intent.resolveActivity(context.getPackageManager()) != null) {
                context.startActivity(intent);
            } else {//没有应用市场，通过浏览器跳转到Google Play
                Intent intent2 = new Intent(Intent.ACTION_VIEW);
                intent2.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + context.getPackageName()));
                if (intent2.resolveActivity(context.getPackageManager()) != null) {
                    context.startActivity(intent2);
                }
            }
        } catch (ActivityNotFoundException activityNotFoundException1) {
            Log.e("TAG", "GoogleMarket Intent not found");
        }
    }

    /**
     * 跳转浏览器
     * @param context app
     */
    public static void startBrowserNow(Context context,String url){
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            context.startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 判断服务是否在运行
     *
     * @param mContext  上下文
     * @param className 　　Service.class.getName();
     */
    public static boolean isServiceRunning(@NonNull Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(50);
        if (serviceList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className)) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }


    /**
     * 判断进程是否运行
     *
     * @param context     上下文
     * @param processName 应用程序的主进程名一般为包名
     * @return
     */
    public static boolean isProcessRunning(Context context, String processName) {
        boolean isRunning = false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> lists = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : lists) {
            if (info.processName.equals(processName)) {
                isRunning = true;
            }
        }
        return isRunning;
    }

    /**
     * 重启app
     * @param context
     */
    public static void restartApp(Context context) {
        PackageManager packageManager = context.getPackageManager();
        if (null == packageManager) {
            return;
        }
        final Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
        if (intent != null) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(intent);
        }
    }


    /**
     * 启动新的app
     *
     * @param context
     * @param packageName
     */
    public static void launchApp(Context context, String packageName) {
        try {
            if (hasApp(context, packageName)) {
                Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
                context.startActivity(intent);
            } else {
                Intent intent2 = new Intent(Intent.ACTION_VIEW);
                intent2.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + packageName));
                if (intent2.resolveActivity(context.getPackageManager()) != null) {
                    context.startActivity(intent2);
                }
            }
        } catch (Exception e) {
            ToastUtil.INSTANCE.show(context,e.getMessage());
            e.printStackTrace();
        }

    }

    public static boolean hasApp(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        List<String> packageNames = new ArrayList<>();
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        return packageNames.contains(packageName);
    }

    /**
     * 获得设备的AndroidId
     *
     * @param context 上下文
     * @return 设备的AndroidId
     */
    public static String getAndroidId(Context context) {
        String newDeviceId = "";
        try {
            String instanceId = getPhoneBrand()+getPhoneModel()+ UUID.randomUUID().toString();
            newDeviceId = md5(instanceId);
            //弃用 获取系统id方式 ,使用自定义id
//            return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception ex) {
            newDeviceId = StrUtil.getRandomStr();
        }
        return newDeviceId;
    }

    /**
     * 获取手机型号
     */
    public static String getPhoneModel() {
        String model = "";
        try {
            model = Build.MODEL;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }

    /**
     * 获取手机品牌
     */
    public static String getPhoneBrand() {
        String brand = "";
        try {
            brand = Build.BRAND;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return brand;
    }


    /**
     * 手机是否开启位置服务
     * 如果没有开启那么所有app将不能使用定位功能
     *
     * @param context 上下文
     */
    public static boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    /**
     * 获取Sim卡国家码
     *
     * @return cn us
     */
    public static String getSimCountryCode(Context context) {
        TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (null == telManager || null == telManager.getSimCountryIso())
            return "";
        return telManager.getSimCountryIso();
    }
}
